<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import {
  GetExamEvaluationsApi,
  AddCourseEvaluationApi,
  GetMyExamEvaluationsApi,
  DeleteCourseEvaluationsApi
} from '@/api/course'
import { Dialog } from '@/components/Dialog'
import { selectionType } from '@/api/login/types'
import { ref, unref, reactive } from 'vue'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ElTabs, ElTabPane, ElProgress } from 'element-plus'
import { BaseButton } from '@/components/Button'
import { useButtonPermiss } from '@/utils/buttonpermiss'
import { useRouter } from 'vue-router'
const { push } = useRouter()
const haspermiss = ref<String[]>([])
const getUseButtonPermiss = () => {
  useButtonPermiss().then((res) => {
    haspermiss.value = res
  })
}
getUseButtonPermiss()
const { t } = useI18n()
const activeName = ref('first')
const columns: TableColumn[] = [
  {
    field: 'selection',
    type: 'selection',
    table: {
      type: 'selection'
    }
  },
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'courseName',
    label: '课程名称',
    sortable: true
  },

  {
    field: 'courseUserName',
    label: '讲师',
    sortable: true
  },
  {
    field: 'userName',
    label: '评价人',
    sortable: true
  },
  {
    field: 'courseAddress',
    label: '考试地址'
  },
  {
    field: 'evaluationContent',
    label: '评价内容'
  },
  {
    field: 'evaluationTime',
    label: '评价时间',
    sortable: true
  },
  {
    field: 'userSign',
    label: '签名',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            {row.userSign ? (
              <img
                src={row.userSign}
                alt="签名图片"
                class="img"
                style={{ width: '100px', height: '100px' }}
              />
            ) : null}
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    align: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => clickimg(data.row.userSign)}>
              查看签名信息
            </BaseButton>
            {haspermiss.value.includes('删除') ? (
              <BaseButton type="danger" onClick={() => delData(data.row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            ) : null}
          </>
        )
      }
    }
  }
]
const columns1: TableColumn[] = [
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'courseName',
    label: '课程名称',
    sortable: true
  },

  {
    field: 'courseUserName',
    label: '讲师',
    sortable: true
  },
  {
    field: 'userName',
    label: '评价人',
    sortable: true
  },
  {
    field: 'courseAddress',
    label: '考试地址'
  },
  {
    field: 'evaluationContent',
    label: '评价内容'
  },
  {
    field: 'evaluationTime',
    label: '评价时间',
    sortable: true
  },
  {
    field: 'userSign',
    label: '签名',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            {row.userSign ? (
              <img src={row.userSign} class="img" style={{ width: '100px', height: '100px' }} />
            ) : null}
          </>
        )
      }
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    align: 'center',
    fixed: 'right',
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => clickimg(data.row.userSign)}>
              查看签名信息
            </BaseButton>
          </>
        )
      }
    }
  }
]
const dialogVisible = ref(false)
const currentimg = ref()
const clickimg = (img) => {
  console.log('点击图片', img)
  currentimg.value = img
  dialogVisible.value = true
}

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    let res
    if (activeName.value == 'first') {
      res = await GetMyExamEvaluationsApi({
        pageNo: unref(currentPage),
        pageRow: unref(pageSize),
        pageModel: { ...unref(searchParams) }
      })
    } else {
      res = await GetExamEvaluationsApi({
        pageNo: unref(currentPage),
        pageRow: unref(pageSize),
        pageModel: { ...unref(searchParams) }
      })
    }

    const list = res.data.pageModels || []

    return {
      list: list,
      total: res.data.totalCount || 0
    }
  },
  fetchDelApi: async () => {
    const res = await DeleteCourseEvaluationsApi(unref(ids))
    return !!res
  }
})
const courseList = ref<selectionType[]>([])
// const GetDoneCourses = async () => {
//   const res = await GetDoneCoursesApi()
//   let typeList: selectionType[] = []
//   res.data?.map((item) => {
//     typeList.push({
//       label: item.courseName,
//       value: item.guid
//     })
//   })
//   courseList.value = typeList
// }
// GetDoneCourses()
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods
const searchParams = ref({})
const setSearchParams = (params: any) => {
  if (params.date) {
    params.startTime = params.date[0]
    params.endTime = params.date[1]
    delete params.date
  }
  searchParams.value = params
  getList()
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'courseName',
    label: '考试名称',
    component: 'Input',
    componentProps: {
      placeholder: '请输入考试名称'
    }
  },

  {
    field: 'date',
    label: t('problem.time'),
    component: 'DatePicker',
    componentProps: {
      style: { width: '340px' },
      type: 'datetimerange',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      StartPlaceholder: 'Start date',
      EndPlaceholder: 'End date'
    }
  }
])
const handleClick = (name) => {
  console.log(name)
  activeName.value = name
  getList()
}
const delLoading = ref(false)
const ids = ref<string[]>([])
const delData = async (row) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.guid] : elTableExpose?.getSelectionRows().map((v) => v.guid) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const AddAction = () => {
  push({ path: '/addevalate/addevalate', query: { type: 'exam' } })
}
</script>

<template>
  <ContentWrap>
    <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
      <el-tab-pane label="我评价的考试" name="first">
        <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
        <div class="mb-10px">
          <BaseButton type="primary" @click="AddAction" v-if="haspermiss.includes('新增')">{{
            t('exampleDemo.add')
          }}</BaseButton>
          <BaseButton
            :loading="delLoading"
            type="danger"
            @click="delData(null)"
            v-if="haspermiss.includes('删除')"
          >
            {{ t('exampleDemo.del') }}
          </BaseButton>
        </div>
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :reserveIndex="true"
          :columns="columns"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :height="600"
          :pagination="{
            total
          }"
        />
      </el-tab-pane>
      <el-tab-pane label="评价我的考试" name="second">
        <Search :schema="searchSchema" @reset="setSearchParams" @search="setSearchParams" />
        <Table
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :reserveIndex="true"
          :columns="columns1"
          :data="dataList"
          :loading="loading"
          @register="tableRegister"
          :height="600"
          :pagination="{
            total
          }"
        />
      </el-tab-pane>
    </el-tabs>
    <Dialog title="签名信息" v-model="dialogVisible">
      <img :src="currentimg" style="width: 100%; height: 100%" />
      <template #footer>
        <a class="downstyle" :href="currentimg" download="签名信息.png">下载签名</a>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
<style scoped>
.clome {
  display: flex;
  flex-direction: column;
}
.percentage-value {
  display: block;
  margin-top: 10px;
  font-size: 24px;
}
.percentage-label {
  display: block;
  margin-top: 10px;
  font-size: 10px;
}
.img {
  cursor: pointer;
}

.downstyle {
  margin-right: 20px;
  display: inline-flex;
  justify-content: center;
  align-items: center;
  line-height: 1;
  height: 32px;
  white-space: nowrap;
  cursor: pointer;
  color: #fff;
  text-align: center;
  box-sizing: border-box;
  outline: 0;
  transition: 0.1s;
  font-weight: 500;
  -webkit-user-select: none;
  user-select: none;
  vertical-align: middle;
  -webkit-appearance: none;
  background-color: #409eff;
  border: var(--el-border);
  border-color: #409eff;
  padding: 8px 15px;
  font-size: 14px;
  border-radius: 4px;
  text-decoration: none;
}
</style>
